var express = require("express");
var { clearListModel } = require("../db/clear");
var router = express.Router();
const jwt = require("jsonwebtoken");

//获取数据
router.get("/list", async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const skip = (page - 1) * pageSize;

    const data = await clearListModel.find().skip(skip).limit(pageSize);

    const total = await clearListModel.countDocuments();
    let token = req.headers.authorization;
    jwt.verify(token, "123456789", (err) => {
      if (!token) {
        return res.send({
          code: 401,
          message: "请先登录",
        });
      } else if (err && err.message === "jwt expired") {
        return res.send({
          code: 401,
          message: "token已过期",
        });
      }
      console.log(data);
      res.send({
        code: 200,
        data,
        total,
        page,
        pageSize,
        hasMore: skip + data.length < total,
        message: "获取成功",
      });
    });
  } catch (error) {
    console.error("获取数据失败:", error);
    res.status(500).send({
      code: 500,
      message: "获取数据失败",
    });
  }
});

module.exports = router;
